package com.sindvision.cces.shiro;

import com.sindvision.cces.beans.User;
import com.sindvision.cces.service.IUserSV;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @Author: chenjintao
 * @Date: 2019-11-22 17:04
 */
@Component
public class MysqlRealm extends AuthorizingRealm {

    @Autowired
    private IUserSV userSV;


    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        String password = new String((char[]) ((char[]) token.getCredentials()));
        User currentUser = userSV.getUserByUserName(username);
        if (currentUser == null) {
            throw new UnknownAccountException();
        } else if (!currentUser.getPassword().equals(password)) {
            throw new IncorrectCredentialsException();
        } else {
            SecurityUtils.getSubject().getSession().setAttribute(User.SESSION_ATTR_NAME, currentUser);
            return new SimpleAuthenticationInfo(username, password, this.getName());
        }
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return new SimpleAuthorizationInfo();
    }
}
